import 'package:device_info/device_info.dart';
import 'package:flutter/material.dart';
import '../../model/appversion.dart';
import 'app_update.dart';
import '../../helper/channelHelper.dart';
import '../../model/user.dart';
import '../../helper/uidata.dart';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LoginPage extends StatefulWidget {
  @override
  LoginPageState createState() => new LoginPageState();
}

class LoginPageState extends State<LoginPage> {
  final TextEditingController c1 =  TextEditingController();
  final TextEditingController c2 =  TextEditingController();
  final key =  GlobalKey<ScaffoldState>();
  final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();

  final lineBorder = const OutlineInputBorder(
    /*边角*/
    borderRadius: BorderRadius.all(
      Radius.circular(8.0), //边角为30
    ),
    borderSide: BorderSide(
      color: Colors.blue, //边线颜色为黄色
      width: 1, //边线宽度为2
    ),
  );

  late SharedPreferences localFile;

  Future getUser(String u1, String p1) async {
    var dio = new Dio();
    var aID = await deviceInfoPlugin.androidInfo;

    dio.options.baseUrl = UIData.apiServer;

    // Response response = await dio
    //     .get("/Login/Account3?username=" + u1 + "&" + "password=" + p1);
    Response response = await dio.get("/Login/Account3?username=" +
        u1 +
        "&password=" +
        p1 +
        "&aID=" +
        aID.androidId);

    if (response.statusCode == 200 && response.data != null) {
      print(response.toString());
      if (response.toString().contains("用户名或密码错误")) {
        await ChannelHelper.showToast("用户名或密码错误");
        return;
      }

      if (response.toString().contains("设备不符")) {
        await ChannelHelper.showToast("账号与绑定的设备不符！");
        return;
      }

      var u1 = new User.fromJson(response.data["User"]);

      if (u1.Id > 0) {
        if (localFile != null) {
          localFile.setString("username", u1.UserName);
          localFile.setString("password", u1.PassWord);
        }

        UIData.CurrentUser = u1;
        UIData.IfLogin = true;
        UIData.token = response.data["Token"];
        Navigator.of(context).pushReplacementNamed(UIData.homeRoute);
      }
    }
  }

  @override
  void initState() {
    // TODO: implement initState

    checkVersion();

    super.initState();
  }

  void checkVersion() async {
    var xx = await AppVersion.GetNew(UIData.appGuid);
    if (xx == null) {
      getLocal();
      return;
    }

    if (xx.VersionCode <= UIData.appVersion) {
      getLocal();
    } else {
      // Navigator.of(context).pushReplacementNamed(UIData.SystemUpdateRoute);
      Navigator.of(context).pushReplacement(MaterialPageRoute(
          builder: (BuildContext context) => AppUpdatePage(xx)));
    }
  }

  void getLocal() async {
    localFile = await SharedPreferences.getInstance();
    String? u1 = localFile.getString("username");
    String? p1 = localFile.getString("password");
    if (u1 != null && p1 != null) getUser(u1, p1);
  }

  getInput(String title, TextEditingController xx, bool mima) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 16.0, horizontal: 30.0),
      //color: Colors.white,
      child: TextField(
        obscureText: mima,
        style: TextStyle(color: Colors.white),
        maxLines: 1,
        controller: xx,
        decoration: InputDecoration(
          //  enabled: true,
          enabledBorder: lineBorder,
          border: lineBorder,
          // hintText: "输入用户名",
          // hintStyle: TextStyle(color: Colors.blue, height: 1.6),
          labelText: title,
          labelStyle: TextStyle(color: Colors.blue),
        ),
      ),
    );
  }

  getButton() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 0.0, horizontal: 30.0),
      width: double.infinity,
      margin: EdgeInsets.only(top: 12.0),
      child: ElevatedButton(
        child: Text(
          "登录",
          style: TextStyle(color: Colors.white, fontSize: 16.0),
        ),
        onPressed: () {
          getUser(c1.text, c2.text);
          // Navigator.pop(context);
          //Navigator.of(context).pushReplacementNamed(UIData.homeRoute);
          // Navigator.pushNamed(context, UIData.homeRoute);
          // Navigator.of(context).pushAndRemoveUntil(new MaterialPageRoute(builder: (context)=>new IndexPage()) ,  ModalRoute.withName(UIData.homeRoute),);
        },
      ),
    );
  }

  getHeader() {
    return Container(
      margin: EdgeInsets.only(bottom: 48.0),
      child: Text(
        UIData.appName,
        style: TextStyle(
            fontWeight: FontWeight.w400, color: Colors.white, fontSize: 24.0),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        //backgroundColor: Colors.white,
        key: key,
        body: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage("lib/assets/images/bg.png"),
              fit: BoxFit.cover,
            ),
            color: Colors.transparent,
          ),
          child: Center(
            child: loginFields(context),
          ),
        ));
  }

  loginBody(BuildContext context) => SingleChildScrollView(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[loginFields(context)],
        ),
      );

  loginFields(BuildContext context) => SingleChildScrollView(
        child: Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              getHeader(),
              getInput("用户名", c1, false),
              getInput("密码", c2, true),
              SizedBox(
                height: 30.0,
              ),
              getButton(),
              SizedBox(
                height: 5.0,
              ),
            ],
          ),
          margin: EdgeInsets.all(12.0),
        ),
      );
}
